package com.meibao.auth.web;

import com.meibao.auth.config.JwtProperties;
import com.meibao.auth.entity.UserInfo;
import com.meibao.auth.service.AuthService;
import com.meibao.auth.utils.JwtUtils;
import com.meibao.common.enums.ExceptionEnums;
import com.meibao.common.exception.MbException;
import com.meibao.common.utils.CookieUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

@RestController
@EnableConfigurationProperties(JwtProperties.class)
public class AuthController {

    @Autowired
    private AuthService authService;

    @Autowired
    private JwtProperties prop;

    @Value("${mb.jwt.cookieName}")
    private String cookieName;
    /**
     * 的登录授权功能
     * @param username
     * @param password
     * @return
     */
    @PostMapping("login")
    public ResponseEntity<Void> login(
            @RequestParam("username") String username, @RequestParam("password") String password,
            HttpServletResponse response, HttpServletRequest request
     ){
        //登录
        String token = authService.login(username, password);
        // 写入cookie
        CookieUtils.newBuilder(response).httpOnly().request(request).build(cookieName, token);
        return ResponseEntity.status(HttpStatus.NO_CONTENT).build();
    }

    @GetMapping("verify")
    public ResponseEntity<UserInfo> verify(@CookieValue("MB_TOKEN") String token,
            HttpServletResponse response, HttpServletRequest request
    ){
        if(StringUtils.isBlank(token)){
            //没有token证明未登陆
            throw new MbException(ExceptionEnums.UNAUTHORIZED);
        }
        try {
            //解析token
            UserInfo userInfo = JwtUtils.getInfoFromToken(token, prop.getPublicKey());
            //刷新token
            String newToken = JwtUtils.generateToken(userInfo, prop.getPrivateKey(), prop.getExpire());
            //重新写入cookie
            CookieUtils.newBuilder(response).httpOnly().request(request).build(cookieName, newToken);
            return ResponseEntity.ok(userInfo);
        }catch (Exception e){
            //token已过期  或者被篡改
            throw new MbException(ExceptionEnums.UNAUTHORIZED);
        }
    }
}
